var playlist = new Array();
//var ytplayer;


$(document).ready(function() {
	_run();
	initSlide();
	$("#tabs").tabs();
		$('#txtRicerca').keypress(function(event) {
				if (event.keyCode == '13') {
					ricercavideo();
				}
			});
		loadPlaylist();
	});
// google.setOnLoadCallback(_run);


function initSlide() {

}
/**
 * Carica la playolist da backend : playlist.php
 * Torna un elenco di videoid (formato json)
 */
function addToPlaylist(videoId, booleanValue ) {
	$.ajax({
		  url: 'playlist.php?operation=add&videoId='+videoId,
		  success: function(data) {
		    $('.result').html(data);
		    //alert('Load was performed.');
		    renderPlaylist();
		  }
		});
	return false;

}
/**
 * Carica la playolist da backend : playlist.php
 * Torna un elenco di videoid (formato json)
 */
function loadPlaylist() {
	$.getJSON('playlist.php', function(data) {
			i = 0;
			$.each(data, function(i, item) {
				playlist[i++] = item.videoid;
				// alert(item.videoid);
				});
			renderPlaylist();
	});

}

function renderPlaylist() {
	listPlaylist="";
	
	$.each(playlist, function(i, item) {
		listPlaylist=listPlaylist+'<li>'+item+'</li>';
		
	});
	//alert("render"+listPlaylist);
	$('#risultatoplaylist').html('<ul>'+listPlaylist+'</ul>');
}


/**
 * Carica un video nel player di youtube
 * @param videoID
 * @return
 */
function loadVideo(videoID, title) {
	//alert(videoID);
	mytplayer = document.getElementById("myytplayer");
	if (ytplayer) {
		mytplayer.loadVideoById(videoID);
		//$('#videoShare').html('<iframe src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D'+videoID+'&amp;layout=standard&amp;show_faces=true&amp;width=450&amp;action=like&amp;colorscheme=light&amp;height=80" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:450px; height:80px;" allowTransparency="true"></iframe>');
		$('#videoShare').html('<iframe src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D'+videoID+'&amp;layout=box_count&amp;show_faces=true&amp;width=450&amp;action=like&amp;colorscheme=light&amp;height=65" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:450px; height:65px;" allowTransparency="true"></iframe>');
		$('#videoTitle').html(title);
	} else {
		alert("player not valid");
	}
	return false;
}

// This function is called when the player changes state
// This function is automatically called by the player once it loads
function onYouTubePlayerReady(playerId) {
	//alert(playerId);
	ytplayer = document.getElementById("myytplayer");
	// This causes the updatePlayerInfo function to be called every 250ms to
	// get fresh data from the player
	// setInterval(updatePlayerInfo, 250);
	// updatePlayerInfo();
	ytplayer.addEventListener("onStateChange", "onPlayerStateChange");
	// ytplayer.addEventListener("onError", "onPlayerError");
}

function onPlayerStateChange(newState) {
	$("#statocorrente").html("nuovo stato:" + newState);
	if (newState == 0) {
		$("#statocorrente").html(" Finito");
	}
}
/*
 * $(function() { $("#tabs").tabs(); });
 */
// The "main method" of this sample. Called when someone clicks "Run".
function loadPlayer() {
	// The video to load
	var videoID = "ylLzyHk54Z0"
	// Lets Flash from another domain call JavaScript
	var params = {
		allowScriptAccess : "always"
	};
	// The element id of the Flash embed
	var atts = {
		id : "myytplayer"
	};
	// All of the magic handled by SWFObject
	// (http://code.google.com/p/swfobject/)
	swfobject.embedSWF("http://www.youtube.com/v/" + videoID
			+ "&enablejsapi=1&rel=0&fs=1&playerapiid=ytplayer", "videoDiv", "185", "150",
			"8", null, null, params, atts);
}
function _run() {
	loadPlayer();
	loadPlaylist();
}

function makeRowResult(item, counter) {
	var id = item['id']['$t'];
	var titolo = item.title.$t;
	var visualizzazioni = item.yt$statistics.viewCount.valueOf();
	var title = item.title.$t;
	var thumbnailUrl = item.media$group.media$thumbnail[0].url;
	var playerUrl = item.media$group.media$player.url;
	var videoId = item.media$group.yt$videoid.$t;
	
	var element = $('<li/>')
	.append(
		$('<img/>')
		.attr('src', thumbnailUrl)
		.attr('width', 130)
		.attr('height', 97)
		.attr('align', 'top')
	)
	.append('<br/>')
	.append(
			$('<a/>')
			.attr('href', '#')
			.attr('onClick', "return loadVideo('"+videoId+"', '"+title+"')")
			.attr('class', 'fg-button ui-state-default fg-button-icon-solo ui-corner-all ui-state-active')
			.attr('title', 'Play This')
			.text('Play This')
	)
	.append('<br/>')
	.append(
			$('<a/>')
			.attr('href', '#')
			.attr('onClick', "return addToPlaylist('"+videoId+"', true)")
			.attr('class', 'fg-button ui-state-default fg-button-icon-solo ui-corner-all ui-state-active')
			.attr('title', 'Add To Play list')
			.text('Add To Play list')
	);
	
	return element;
}

function ricercavideo() {
	var stringaricerca = $("#txtRicerca").val().replace(' ', '+');
	var url = 'http://gdata.youtube.com/feeds/api/videos?q=' + stringaricerca + '&max-results=10&format=5&v=2&alt=json-in-script&callback=?';

	$.getJSON(url, function(data) {
		$('#carousel_search').remove();
		$('<ul/>').attr('id', 'carousel_search').appendTo('#risultatoricerca');
		$.each(data.feed.entry, function(i, item) {
			$('#carousel_search').append(makeRowResult(item, i));
		}); // fine for each
	});
}